package org.bpms.controller.admin;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bpms.model.admin.Btype;
import org.bpms.model.admin.Suser;
import org.bpms.plugins.bjui.BjuiRender;
import org.bpms.service.admin.LogService;
import org.bpms.service.admin.TypeService;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

import com.jfinal.aop.Enhancer;
import com.jfinal.core.Controller;
/**
 * 文档类型控制器
 * @author hupei
 *
 */
public class TypeController extends Controller {
	private LogService  logService = Enhancer.enhance(LogService.class);
	private TypeService typeService = Enhancer.enhance(TypeService.class);
	
	/**
	 * 全部类型
	 */
	public void index(){
		List<Btype> lb = typeService.allType();
		setAttr("types", lb);
		render("/admin/type/type.html");
	}
	
	/**
	 * 保存
	 */
	public void save(){
		Map<String, Object> map = new HashMap<String , Object>();
		Btype type = getModel(Btype.class);
		typeService.saveOrUpdate(type);
		Suser user = getSessionAttr("user");
		logService.create(user.getStr("username"), "新增类型:"+type.getStr("text"));
		map.put("success", true);
		map.put("obj", type);
		renderJson(map);
	}
	
	/**
	 * 保存类型用户关系
	 */
	public void typeUserSave(){
		String users = getPara("users");
		String typeId = getPara("typeid");
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> jsonmap = new HashMap<String , Object>();	
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		Map map = null;
		try {
			map = mapper.readValue(users, Map.class);
			if (null != map){
				typeService.updateUserRelation(map, typeId);
			}
		} catch (IOException e) {
			render(BjuiRender.error("保存失败！" , false));
			e.printStackTrace();
		}
		render(BjuiRender.success("保存成功！" , false));		
	}
	
	/**
	 * 删除类型
	 */
	public void remove(){
		Map<String, Object> map = new HashMap<String , Object>();
		String typeId = getPara("id");
		Btype type = Btype.me.findById(typeId);
		Suser user = getSessionAttr("user");
		logService.create(user.getStr("username"), "删除类型:"+type.getStr("text"));
		typeService.del(typeId);
		map.put("success", true);
		renderJson(map);
	}
}
